/**
 * Created by xxx on 2017/7/6.
 */
//用react封装
var currentpage = 1,totlepage = 1,i;//分页的当前页和总的页数
//表单的最高高度、当前第几页、总页数、总行数
var otherData = {pageLeft:0,pageRight:0};
//分页
var Page = React.createClass({
    setPage: function (e) {
        setPage($(e.target).html());
        this.props.onPageClick(1);
    },
    showPage: function () {
        showPage();
    },
    render: function () {
        {
            var items = [],
                svar = this;
            if(totlepage == 0 ){
                items.push({num:1,checked:true})
            }else if(totlepage < 6){
                for(i = 1;i <= totlepage ;i++) {
                    if (i == currentpage) {
                        items.push({num:i,checked:true})
                    } else {
                        items.push({num:i,checked:false})
                    }
                }
            }else if(currentpage >= (totlepage-2)) {//点在左边
                items.push({num:1,checked:false});
                items.push({num:'···',checked:false});
                for(i = totlepage-2;i <= totlepage ;i++){
                    if(i == currentpage){
                        items.push({num:i,checked:true})
                    }else{
                        items.push({num:i,checked:false})
                    }
                }
            }else if(currentpage <= 3){
                for(i = 1;i <= 3 ;i++) {
                    if (i == currentpage) {
                        items.push({num:i,checked:true})
                    } else {
                        items.push({num:i,checked:false})
                    }
                }
                items.push({num:'···',checked:false});
                items.push({num:totlepage,checked:false})
            }else {//点在两边
                items.push({num:1,checked:false});
                items.push({num:'···',checked:false});
                items.push({num:currentpage-1,checked:false});
                items.push({num:currentpage,checked:true});
                items.push({num:currentpage+1,checked:false});
                items.push({num:'···',checked:false});
                items.push({num:totlepage,checked:false})
            }
        }
        return (
            <div className="studentsInfo-page tableInfo-page">
                <div className="page-number">每页<span className="page-number-list" onClick={this.showPage}>{pagecount}</span>条</div>
                <div className="page-list" style={{top:pageListTop+"px"}}>
                    <ul>
                        {
                            pageList.map(function (item) {
                                return (<li onClick={svar.setPage}>{item}</li>)
                            })
                        }
                    </ul>
                </div>
                <div className="page-limit">
                    <ol className="page-limit-ol">
                        <li className="page-limit-img" name="-1" onClick={otherData.pageLeft == 0?'':svar.props.onPageClick.bind(svar,-1)} ><span className={otherData.pageLeft == 0?'page-limit-left-no':'page-limit-left-yes'}/></li>
                        {
                            items.map(function (item) {
                                return (<li onClick={isNaN(item.num)?'':svar.props.onPageClick.bind(svar,item.num)} className={item.checked == true?'page-limit-num page-limit-checked':'page-limit-num'} name={item.num}>{item.num}</li>)
                            })
                        }
                        <li className="page-limit-img" name="-2" onClick={otherData.pageRight == 0?'':svar.props.onPageClick.bind(svar,-2)}><span className={otherData.pageRight == 0?'page-limit-right-no':'page-limit-right-yes'}/></li>
                    </ol>
                </div>
            </div>
        );
    },
});

//父组件
var Main = React.createClass({
    //组件初始状态
    getInitialState: function () {
        return {
            otherData: this.props.otherData,
            tableData: [],//显示表单的数据
            timeQueryData: [],//积分概况查询的数据
            telQueryData: [],//教师手机号查询的数据
            telPageInfo: {
                currentpage:1,//当前页
                pageLeft: 0,//0是不可点击，1反之
                pageRight: 0,//0是不可点击，1反之
                totlepage: 1,//总页数
            },//积分概况查询的数据分页信息
            timePageInfo: {
                currentpage:1,//当前页
                pageLeft: 0,//0是不可点击，1反之
                pageRight: 0,//0是不可点击，1反之
                totlepage: 1,//总页数
            },//教师手机号查询的数据分页信息
            creditData: [
                {id:1,name:'累计领取',number:''},
                {id:2,name:'累计消费',number:''},
                {id:3,name:'今日领取',number:''},
                {id:4,name:'今日消费',number:''},
                ],//总积分概况
            menuType: 1,//1:积分概况 2：搜索
            timeTabelHeader: [],

        }
    },
    componentDidMount: function () {
        var svar = this;
        suixun.hideLoding();//显示加载中
        suixun.ajax(serverUrl+'/credits/task/find_all_name.json','',"get",function(data){
            if(data.code == 200){
                svar.setState({timeTabelHeader:data.info.list})
            }else{
                suixun.alert(data.msg);
            }
        });
        this.getAllCredit();
        // this.getTableDate();
        $('.frequencyTime').datetimepicker({
            format: "Y-m-d", //格式化日期
            timepicker: false, //显示时间选项
            todayButton: false, //关闭选择今天按钮
            step:5,//时间间隔
        });
        //绑定回车时间
        $(document).keypress(function(e) {
            var eCode = e.keyCode ? e.keyCode : e.which ? e.which : e.charCode;
            if (eCode == 13){
                if($("#businessQuery").is(":focus")){
                    svar.getTableDate();
                }
            }
        });
    },
    /**
     * 获取总的积分统计
     */
    getAllCredit: function () {
        var svar = this;
        suixun.ajax(serverUrl+'/credits/reord/find_condition.json','',"get",function(data){
            if(data.code == 200){
                var creditData = svar.state.creditData;
                creditData[0].number = data.info.accumulateGet;
                creditData[1].number = data.info.accumulateConsume;
                creditData[2].number = data.info.todayGet;
                creditData[3].number = data.info.todayConsume;
                svar.setState({creditData:svar.state.creditData});
            }else{
                suixun.alert(data.msg);
            }
        });


    },
    /**
     * 获取列表数据
     */
    getTableDate: function(){
        var svar = this;
        var start = 0;
        if(currentpage>1){
            start = (currentpage-1)*pagecount;
        }
        if(this.state.menuType==2){
            var phone = $("#businessQuery").val();
            if(phone==''){
                suixun.alert("教师手机号不能为空！");
                return;
            }else if(phone.length != 11){
                suixun.alert("教师手机号格式错误！");
                return;
            }else if(phone.length > 0 && !/^[1-9]\d*$/.test(phone)){
                suixun.alert("教师手机号格式错误！");
                return;
            }
            $(".input-value").html(phone);
            suixun.showLoding();//显示加载中
            suixun.ajax(serverUrl+'/credits/reord/find_page_tel.json?start='+start+'&length='+pagecount+'&tel='+phone,'',"get",function(data){
                suixun.hideLoding();
                if(data.code == 200){
                    var pageInfo = {};
                    if(data.info.total==0){
                        currentpage = 1;
                        otherData.pageLeft = 0;
                        otherData.pageRight = 0;
                        totlepage = 1;//初始化的时候赋值：分页的当前页和总的页数
                    }else {
                        pageInfo = suixun.getPageInfo(start, pagecount, data.info.total);
                        currentpage = pageInfo.currentpage;
                        otherData.pageLeft = pageInfo.pageLeft;
                        otherData.pageRight = pageInfo.pageRight;
                        totlepage = pageInfo.totlepage;//初始化的时候赋值：分页的当前页和总的页数}
                    }
                    svar.setState({tableData:data.info.list,telQueryData:data.info.list,otherData:otherData,telPageInfo:pageInfo});
                    console.log(svar.state.telPageInfo);
                }else{
                    suixun.alert(data.msg,function (data) {
                        if(data){
                            currentpage = 1;
                            otherData.pageLeft = 0;
                            otherData.pageRight = 0;
                            totlepage = 1;//初始化的时候赋值：分页的当前页和总的页数
                            svar.setState({tableData:[],telQueryData:[],otherData:otherData});
                        }
                    })
                }
            });
        }else{
            var startdate = $("#startdate").val();//开始时间
            var enddate = $("#enddate").val();//结束时间

            if(startdate==''){
                suixun.alert("开始时间不能为空！");
                return;
            }
            if(enddate==''){
                suixun.alert("结束时间不能为空！");
                return;
            }
            if(startdate.replace(/-/g,'')>enddate.replace(/-/g,'')) {
                suixun.alert("开始时间时间不能大于结束时间！");
                return;
            }
            suixun.showLoding();//显示加载中
            suixun.ajax(serverUrl+'/credits/reord/find_page_info.json?start='+start+'&length='+pagecount+'&startDate='+startdate+'&endDate='+enddate,'',"get",function(data){
                suixun.hideLoding();
                if(data.code == 200){
                    var pageInfo = {},tableData = [];
                    if(data.info.total==0){
                        currentpage = 1;
                        otherData.pageLeft = 0;
                        otherData.pageRight = 0;
                        totlepage = 1;//初始化的时候赋值：分页的当前页和总的页数
                    }else {
                        pageInfo = suixun.getPageInfo(start, pagecount, data.info.total);
                        currentpage = pageInfo.currentpage;
                        otherData.pageLeft = pageInfo.pageLeft;
                        otherData.pageRight = pageInfo.pageRight;
                        totlepage = pageInfo.totlepage;//初始化的时候赋值：分页的当前页和总的页数}
                        for(var i = 0;i <data.info.list.length;i++){
                            var taskData = [];
                            for(var j = 1;j <= svar.state.timeTabelHeader.length;j++){//
                                taskData.push(data.info.list[i]['task'+j]);
                            }
                            data.info.list[i]['taskData'] = taskData;//任务列表数据
                            tableData.push(data.info.list[i]);
                        }
                    }
                    svar.setState({tableData:tableData,timeQueryData:tableData,otherData:otherData,timePageInfo:pageInfo});//timeTabelHeader:data.info[0],
                }else{
                    suixun.alert(data.msg,function (data) {
                        if(data){
                            currentpage = 1;
                            otherData.pageLeft = 0;
                            otherData.pageRight = 0;
                            totlepage = 1;//初始化的时候赋值：分页的当前页和总的页数
                            svar.setState({tableData:[],telQueryData:[],otherData:otherData});
                        }
                    })
                }
            });
        }

    },
    /**
     * 分页
     * @param num
     */
    onPageClick: function (num) {
        if(num > 0){
            currentpage = num;
        }else if(num == -1 && currentpage > 1){
            currentpage --;
        }else if(num == -2  && currentpage < totlepage){
            currentpage ++;
        }
        this.getTableDate();
    },
    /**
     * 删除优惠劵
     * @returns {XML}
     */
    onClickDelete: function (bannerId) {
        var svar = this;
        suixun.confirm_noTit("是否确定删除？",function (data) {
            if(data){
                suixun.showLoding();//显示加载中
                var param="param={";
                param = getJsonDataNotEmpty(param,"bannerIds",""+bannerId+"");
                param += "}";
                suixun.ajax(serverUrl+'/banner/deleteBanner.json',param,"get",function(data){
                    suixun.hideLoding();//隐藏加载中
                    if(data.code == 200){
                        suixun.alert('删除成功!',function (data) {
                            if(data){
                                var tbodyData = $("#tbodyData").children();
                                if(tbodyData.length == 1 && currentpage > 1){
                                    totlepage = totlepage - 1;
                                    svar.onPageClick(currentpage-1);//更新数据
                                }else{
                                    svar.onPageClick(currentpage);//更新数据
                                }
                            }
                        });
                    }else{
                        suixun.alert(data.msg);
                    }
                });
            }
        });
    },
    /**
     * 编辑优惠劵
     * @returns {XML}
     */
    onClickEdit: function (id) {

    },

    /**
     * 新增优惠劵
     * @returns {XML}
     */
    onClickAdd: function () {

    },
    /**
     * 点击按钮
     * @return {XML}
     */
    changeMenu: function (type) {
        if(type==1){
            var pageInfo =this.state.timePageInfo;
            currentpage = pageInfo.currentpage;
            otherData.pageLeft = pageInfo.pageLeft;
            otherData.pageRight = pageInfo.pageRight;
            totlepage = pageInfo.totlepage;//初始化的时候赋值：分页的当前页和总的页数}
            this.setState({tableData:this.state.timeQueryData,otherData:otherData,menuType:type});
        }else{
            var pageInfo =this.state.telPageInfo;
            currentpage = pageInfo.currentpage;
            otherData.pageLeft = pageInfo.pageLeft;
            otherData.pageRight = pageInfo.pageRight;
            totlepage = pageInfo.totlepage;//初始化的时候赋值：分页的当前页和总的页数}
            this.setState({tableData:this.state.telQueryData,otherData:otherData,menuType:type});
        }
    },
    /**
     * 导出excel
     * @return {XML}
     */
    export: function () {
        var startdate = $("#startdate").val();//开始时间
        var enddate = $("#enddate").val();//结束时间

        if(startdate==''){
            suixun.alert("开始时间不能为空！");
            return;
        }
        if(enddate==''){
            suixun.alert("结束时间不能为空！");
            return;
        }
        if(startdate.replace(/-/g,'')>enddate.replace(/-/g,'')) {
            suixun.alert("开始时间时间不能大于结束时间！");
            return;
        }
        window.location.href = serverUrl+'/credits/reord/export_get_info?startDate='+startdate+'&endDate='+enddate;
    },
    render: function () {
        {
            var svar = this,trIndex = 0;
            /**
             * 积分统计表单
             */
            var TabelCreditStatistics = this.state.creditData.map(function (data,index) {
                if(data.number){
                    trIndex++;
                }
                return (
                    data.number?
                        <tr>
                            <td style={{width: '20%'}}>{trIndex}</td>
                            <td style={{width: '40%'}}>{data.name}</td>
                            <td style={{width: '40%'}}>{data.number}</td>
                        </tr>
                    :
                        ''
                )
            });
            /**
             * 按照日期搜索
             */
            var timeTabelHeaders = this.state.timeTabelHeader.map(function (data,index) {
                return (
                    <th>{data.name}</th>
                )
            });
            console.log(this.state.tableData);
            console.log(this.state.menuType);
            /**
             * 日期查询积分具体详情、搜索
             */
            var Tabels = this.state.tableData.map(function (data,index) {
                return (
                    svar.state.menuType==1?
                            <tr>
                                <td >{index+1}</td>
                                <td >{data.doDate}</td>
                                <td >{data.etotalNum}</td>
                                {
                                    data.taskData.map(function (dataTask,index) {
                                        return (
                                            <td >{dataTask}</td>
                                        )
                                    })
                                }
                                <td >{data.cumulativeCollection}</td>
                            </tr>
                        :
                            <tr>
                                <td style={{width: '5%'}}>{index+1}</td>
                                <td style={{width: '25%'}}>{data.doTime.substring(0,11)}&nbsp;{data.doTime.substring(11,19).replace(/-/g,'.')}</td>
                                <td style={{width: '20%'}}>{data.name}</td>
                                <td style={{width: '20%'}}>{data.creditNum}</td>
                                <td style={{width: '20%'}}>{data.currentBalance}</td>
                                <td style={{width: '20%'}}>{data.remark}</td>
                            </tr>

                )
            });
        }
        return (
            <div className="tableManage-body">
                <header>
                    <div className="header-left">
                        <div className="header-left-studentInfo">
                            <span className={this.state.menuType==1?"header-left-button menu-width showOrder ":"header-left-button menu-width "} onClick={this.changeMenu.bind(this,1)}>积分概况</span>
                            <span className={this.state.menuType==2?"header-left-button showOrder ":"header-left-button "} onClick={this.changeMenu.bind(this,2)}>搜索</span>
                        </div>
                        <div className="header-left-annotationsInfo">
                            <img src="../img/icon/annotations.png" />
                            <span className="header-left-annotations-arrowsLeft"/>
                            <div className="header-left-annotations">这里是注释。</div>
                        </div>
                    </div>
                </header>

                <div style={this.state.menuType==1?{display:'block'}:{display:'none'}}>
                    <div className="tableInfo">
                        <div className="tableInfo-data">
                            <div className="tableInfo-data-table" >
                                <table className="head-body">
                                    <thead>
                                    <th style={{width: '5%'}}>序号</th>
                                    <th style={{width: '20%'}}>统计项</th>
                                    <th style={{width: '25%'}}>积分数值</th>
                                    </thead>
                                    <tbody>
                                    {this.state.creditData==""?'':TabelCreditStatistics}
                                    </tbody>
                                </table>
                                {this.state.creditData==""?<div className="tableNoData">{tableNoDataCount}</div>:''}
                            </div>
                        </div>
                    </div>
                    <div className="time-query">
                        <div className="query">
                            <span className="checkTime-title">请选择日期</span>
                            <span className="popAddMessage-body-input-content">
                                <input className="frequencyTime beginTime" type="text" placeholder="开始日期"  readonly name="startdate" id="startdate"/>
                            </span>
                            <span className="timeMiddle"/>
                                <span className="popAddMessage-body-input-content" >
                                <input className="frequencyTime endTime" type="text"  placeholder="结束日期"  readonly  name="enddate" id="enddate"/>
                            </span>
                            <span className="header-right-query-button" data-value="1" onClick={this.getTableDate.bind(this)}>搜索</span>
                        </div>
                        <div className="export-button" onClick={this.export.bind(this)}>
                            <span className="export-img">
                                <img src="../img/icon/export.png" />
                            </span>
                            <span className="export-text">导出excel</span>
                        </div>
                    </div>
                </div>
                <div style={this.state.menuType==2?{display:'block'}:{display:'none'}}>
                    <div className="header-query retrieval">
                        <div className="header-query-input">
                            <input className="query-value enterEvent" type="text" id="businessQuery" maxLength="11" placeholder="请输入教师手机号"/>
                        </div>
                        <div className="header-query-img" onClick={this.getTableDate.bind(this)} />
                    </div>
                    <div className="show-query-value">搜索结果：<span className="input-value"></span></div>
                </div>

                <div className="tableInfo">
                    <div className="tableInfo-data">
                        <div className="tableInfo-data-table" >
                            <table className="head-body">
                                {
                                    this.state.menuType==1?
                                            <thead>
                                                <th >序号</th>
                                                <th >日期</th>
                                                <th >今日领取</th>
                                                {timeTabelHeaders}
                                                <th title="项目运行开始到列表数据中对应日期的累积值">累计领取</th>
                                            </thead>
                                        :
                                            <thead>
                                                <th style={{width: '5%'}}>序号</th>
                                                <th style={{width: '25%'}}>日期</th>
                                                <th style={{width: '20%'}}>任务</th>
                                                <th style={{width: '20%'}}>积分变化</th>
                                                <th style={{width: '20%'}}>账户余额</th>
                                                <th style={{width: '20%'}}>备注</th>
                                            </thead>
                                }


                                <tbody>
                                {this.state.tableData==""?'':Tabels}
                                </tbody>
                            </table>
                            {this.state.tableData==""?<div className="tableNoData">{tableNoDataCount}</div>:''}
                        </div>
                    </div>
                    <Page otherData={this.state.otherData} onPageClick={this.onPageClick} />
                </div>
                <footer id="copyright">
                    <span><img src="../img/icon/copyright.png"/>{copyright}</span>
                </footer>
            </div>
        );
    }
});
ReactDOM.render(
    <Main  otherData={otherData} />,
    document.getElementById('tableManage')
);
